var jsontemplate = require('json-template'),
    log = require('oil/log'),
    oil = require('oil');

var readAndTruncate = function(module) {
  var filename = module.fullPath,
      fs = new oil.FileSystem(),
      f;
  try {
    f = fs.open(filename);
  } catch (e) {
    log.error('Error opening %s: %s', filename, e);
    throw e;
  }
  var contents = f.read();
  f.close();
  contents = contents.slice(module.offset);
  return contents;
};

// Makes a module name suitable for use as a variable
var cleanName = function(name) {
  // TODO: Check for . characters, those are invalid
  return name.replace(/[\-\/]/g, '_');
};

var FORMATTERS = {'read-and-truncate': readAndTruncate,
                  'clean-name': cleanName};

exports.write = function(outfile, templateData, dataTree) {
  var contents = dataTree.contentsOf('archive.jsont'),
      t = jsontemplate.fromString(contents, {more_formatters: FORMATTERS});

  // TODO: use t.execute() instead
  // It's annoying that I can't just pass outfile.write directly?
  var archive = t.render(templateData, function(s) { outfile.write(s) });
};

exports.expandMain = function(template, data) {
  t = jsontemplate.Template(template, {more_formatters: FORMATTERS});
  return t.expand(data);
}
